package com.mlizhi.modules.spec.record;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.mlizhi.base.MlzApplication;
import com.mlizhi.base.Session;
import com.mlizhi.kingdom.R;
import com.mlizhi.modules.spec.dao.DaoSession;
import com.mlizhi.modules.spec.dao.DetectDao;
import com.mlizhi.modules.spec.dao.model.DetectModel;
import com.mlizhi.modules.spec.util.DateFormatUtil;
import com.mlizhi.utils.Constants;
import com.mlizhi.widgets.chart.ChartView4Line;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;

public class SpecRecordPartLinerDetailActivity extends Activity {
	//

	private TextView recordItemTitle,selectedTime,timeIndicatorLabel;
	private View view = null;
	
	private DaoSession daoSession;
	private DetectDao detectDao;
	
	private MlzApplication mlzApplication;
	//选择部位类型变量
	private int partType = 0;
	//选择时间类型变量
	private int timeType = 0;
	private Session mSession;
	private String userId;
	private Date currentDate = null,nowDate = null;
	private ChartView4Line chartView4Line = null;
	private TextView averageValuePre,averageValuePost;
	
	
	private String detectType = String.valueOf(Constants.DETECT_TYPE_WATER);
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSession = Session.get(getApplicationContext());
		mlzApplication = (MlzApplication) getApplication();
		this.setContentView(R.layout.activity_spec_record_part_chart);
		/** 发送策略定义了用户由统计分析SDK产生的数据发送回友盟服务器的频率。 */
		MobclickAgent.updateOnlineConfig( this );
		/** 设置是否对日志信息进行加密, 默认false(不加密). */
		AnalyticsConfig.enableEncrypt(true);
		selectedTime = (TextView) findViewById(R.id.id_selected_time_value);
		timeIndicatorLabel = (TextView) findViewById(R.id.id_spec_type_indicator_label);
		chartView4Line = (ChartView4Line) findViewById(R.id.id_chart_line_view);
		averageValuePre = (TextView) findViewById(R.id.id_current_average_value_pre);
		averageValuePost = (TextView) findViewById(R.id.id_current_average_value_post);
		
		daoSession = mlzApplication.getDaoSession();
		detectDao = daoSession.getDetectDao();
		userId = mSession.getUid();
		if(userId == null || "".equals(userId)) {
			userId = mSession.getMac();
		}
		Intent intent = getIntent();
		@SuppressWarnings("unchecked")
		HashMap<String,String> typeMap = (HashMap<String,String>)intent.getSerializableExtra("PartType"); 
		timeType = intent.getIntExtra("TimeType", 0);
		try {
			partType = Integer.parseInt(typeMap.get(Constants.BODY_PART_TYPE));
		} catch (NumberFormatException e) {
			partType = 0;
		}
		recordItemTitle = (TextView) findViewById(R.id.id_spec_record_item_tv);
		
		if(partType == Constants.BODY_PART_EYE){
			recordItemTitle.setText(R.string.bodyParts4eye);
		}else if(partType == Constants.BODY_PART_HAND){
			recordItemTitle.setText(R.string.bodyParts4hand);
		}else if(partType == Constants.BODY_PART_FACE){
			recordItemTitle.setText(R.string.bodyParts4face);
		}else if(partType == Constants.BODY_PART_NECK){
			recordItemTitle.setText(R.string.bodyParts4neck);
		}
		currentDate = DateFormatUtil.formatDate(new Date());	
		nowDate = currentDate;
		initTimeValue(currentDate);
		
	}
	
	
	
	/**
	 * 选择时间：上一天，下一天；上一周，下一周；上一月，下一月。
	 * @param view
	 */
	public void onChoiceChartView(View view) {
		switch (view.getId()) {
		case R.id.id_btn4arrow_left:
			MobclickAgent.onEvent(this,"day2before");
			if(timeType == Constants.BODY_PART_CURRENT_DAY){
				currentDate = DateFormatUtil.getBeforeDay(currentDate);
				MobclickAgent.onEvent(this,"day2before");
			}else if(timeType == Constants.BODY_PART_CURRENT_WEEK){
				currentDate = DateFormatUtil.getBeforeMonthCurrentDate(currentDate);
				MobclickAgent.onEvent(this,"week2before");
			}else if(timeType == Constants.BODY_PART_CURRENT_MONTH){
				currentDate = DateFormatUtil.getBeforeMonthCurrentDate(currentDate);
				MobclickAgent.onEvent(this,"month2before");
			}
			initTimeValue(currentDate);
			break;
		case R.id.id_btn4arrow_right:
			if(currentDate.getTime() < nowDate.getTime()){
				if(timeType == Constants.BODY_PART_CURRENT_DAY){
					currentDate = DateFormatUtil.getNextDay(currentDate);
					MobclickAgent.onEvent(this,"day2after");
				}else if(timeType == Constants.BODY_PART_CURRENT_WEEK){
					currentDate = DateFormatUtil.getNextWeekCurrentDate(currentDate);
					MobclickAgent.onEvent(this,"week2after");
				}else if(timeType == Constants.BODY_PART_CURRENT_MONTH){
					currentDate = DateFormatUtil.getNextMonthCurrentDate(currentDate);
					MobclickAgent.onEvent(this,"month2after");
				}
				initTimeValue(currentDate);
			}else {
				if(timeType == Constants.BODY_PART_CURRENT_DAY){
					Toast.makeText(this, R.string.record_nodata_day, Toast.LENGTH_SHORT).show();
				}else if(timeType == Constants.BODY_PART_CURRENT_WEEK){
					Toast.makeText(this, R.string.record_nodata_week, Toast.LENGTH_SHORT).show();
				}else if(timeType == Constants.BODY_PART_CURRENT_MONTH){
					Toast.makeText(this, R.string.record_nodata_month, Toast.LENGTH_SHORT).show();
				}
			}
			break;
		case R.id.id_spec_record_item_back:
			finish();
			break;
		}
	}
	
	/**
	 * 根据当前实际获取当天，当周，当月显示时间
	 * @param currentDate
	 */
	public void initTimeValue(Date currentDate) {
		
		Date startDate = null;
		Date endDate = null;
		
		if(timeType == Constants.BODY_PART_CURRENT_DAY){
			String nowTime = DateFormatUtil.date2str(currentDate);
			selectedTime.setText(nowTime);
			timeIndicatorLabel.setText(R.string.current_day);
			startDate = currentDate;
			endDate = DateFormatUtil.getNextDay(currentDate);
		}else if(timeType == Constants.BODY_PART_CURRENT_WEEK){
			String currentWeekStr = String.valueOf(DateFormatUtil.date2string(DateFormatUtil.getFirstDayOfWeek(currentDate),this)+" ~ "+DateFormatUtil.date2string(DateFormatUtil.getNextDay(DateFormatUtil.getLastDayOfWeek(currentDate)),this));
			selectedTime.setText(currentWeekStr);
			timeIndicatorLabel.setText(R.string.current_week);
			startDate = DateFormatUtil.getFirstDayOfWeek(currentDate);
			endDate = DateFormatUtil.getLastDayOfWeek(currentDate);
		}else if(timeType == Constants.BODY_PART_CURRENT_MONTH){
			String currentMonthStr = String.valueOf(DateFormatUtil.date2string(DateFormatUtil.getFirstDayOfMonth(currentDate),this)+" ~ "+DateFormatUtil.date2string(DateFormatUtil.getNextDay(DateFormatUtil.getLastDayOfMonth(currentDate)),this));
			selectedTime.setText(currentMonthStr);
			timeIndicatorLabel.setText(R.string.current_month);
			startDate = DateFormatUtil.getFirstDayOfMonth(currentDate);
			endDate = DateFormatUtil.getLastDayOfMonth(currentDate);
		}
		
		initChart(String.valueOf(partType),userId,String.valueOf(startDate.getTime()),String.valueOf(endDate.getTime()));
	}
	
	
	/**
	 * 根据获取检测的数据
	 * @param partType
	 * @param userId
	 * @param startTime
	 * @param endTime
	 */
	private void initChart(String partType,String userId,String startTime,String endTime) {
		List<DetectModel> detectModelPreList = detectDao.queryRaw("WHERE PART_TYPE = ? AND DETECT_TYPE = ? AND USER_ID = ? AND INSERT_TIME > ? AND INSERT_TIME < ? AND NURSER_TYPE = ? ORDER BY _id ASC", 
				new String[]{partType,detectType,userId,startTime,endTime,String.valueOf(Constants.NURSER_TYPE_PRE)});
		List<DetectModel> detectModelPostList = detectDao.queryRaw("WHERE PART_TYPE = ? AND DETECT_TYPE = ? AND USER_ID = ? AND INSERT_TIME > ? AND INSERT_TIME < ? AND NURSER_TYPE = ? ORDER BY _id ASC", 
				new String[]{partType,detectType,userId,startTime,endTime,String.valueOf(Constants.NURSER_TYPE_POST)});
		if(detectModelPreList != null && detectModelPreList.size() > 1) {
			float points4pre[] = new float[detectModelPreList.size()];
			int i=0;
			float sumValue = 0.0f;
			for(DetectModel detectModel : detectModelPreList){
				points4pre[i] = (float) (detectModel.getDetectValue() * 0.1f);
				sumValue += points4pre[i];
				i++;
			}
			averageValuePre.setText(String.valueOf(Math.ceil(sumValue/detectModelPreList.size() * 1000)/10f + "%"));
			chartView4Line.setPoints4pre(points4pre);
//			chartView4Line.invalidate();
		}else{
			chartView4Line.setPoints4pre(new float[]{0.0f});
			averageValuePre.setText(String.valueOf("0.0%"));
		}
		if(detectModelPostList != null && detectModelPostList.size() >1)  {
			float points4post[] = new float[detectModelPostList.size()];
			int j=0;
			float sumValue = 0.0f;
			for(DetectModel detectModel : detectModelPostList){
				points4post[j] = (float) (detectModel.getDetectValue() * 0.1f);
				sumValue += points4post[j];
				j++;
			}
			averageValuePost.setText(String.valueOf(Math.ceil(sumValue/detectModelPostList.size() * 1000)/10f + "%"));
			chartView4Line.setPoints4post(points4post);
//			chartView4Line.invalidate();
		}else{
			averageValuePost.setText(String.valueOf("0.0%"));
			chartView4Line.setPoints4post(new float[]{0.0f});
		}
		chartView4Line.invalidate();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
	}
	
	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("SplashScreen"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写)
	    MobclickAgent.onResume(this);          //统计时长
	}

	@Override
	public void onPause() {
		super.onPause();
		 MobclickAgent.onPageEnd("SplashScreen"); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息 
		    MobclickAgent.onPause(this);
	}
	
}
